const {app, BrowserWindow, ipcMain} = require('electron');
const path = require('path');
const registerDBIpc = require('./ipc/dbHandler');
const registerQUESIpc = require('./ipc/quesHandler');

function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        autoHideMenuBar: true,  // 自动隐藏菜单栏
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            contextIsolation: true,
            nodeIntegration: false,
        }
    });

    win.loadFile('pages/index.html');

    // 确认退出
    if (process.platform !== 'darwin') {
        win.on('close', (e) => {
            const choice = require('electron').dialog.showMessageBoxSync(win, {
                type: 'question',
                buttons: ['否', '是'],
                defaultId: 0,
                cancelId: 0,
                title: '确认退出',
                message: '确定要退出应用吗？'
            });

            if (choice !== 1) {
                // 阻止关闭
                e.preventDefault();
            }
        });
    }
}

function registerIpcHandlers() {
    registerDBIpc(); // 数据库模块
    registerQUESIpc(); // 考题模块
}

app.whenReady().then(() => {
    createWindow();

    // 注册各模块的IPC
    registerIpcHandlers();

    // 适配MacOS窗口激活行为
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

// 适配MacOS关闭窗口行为
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
});